package mywebapps.dao.hibernate;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;

import javax.inject.Named;

import mywebapps.common.utils.HibernateUtil;
import mywebapps.dao.ArtProductDao;
import mywebapps.model.ArtProduct;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

@Named("artProductDao")
public class ArtProductDaoImpl implements ArtProductDao {

	@Override
	public void createArtProduct(ArtProduct product) {
		SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
		Session session = factory.openSession();
		session.beginTransaction();
		Timestamp now = new Timestamp(Calendar.getInstance().getTimeInMillis());
		product.setDateAdded(now);
		product.setLastUpdateTst(now);
		product.setLastUpdateUser("CHANGETHIS");
		session.save(product);
		session.getTransaction().commit();
	}

	@Override
	public List<ArtProduct> getAllArtProducts() {
		SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
		Session session = factory.openSession();
		Query query = session.getNamedQuery("ArtProduct.getAll");
		return query.list();
	}

	@Override
	public List<ArtProduct> getArtProducts(String type) {
		SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
		Session session = factory.openSession();
		Query query = session.getNamedQuery("ArtProduct.getByType");
		query.setString("type", type);
		return query.list();
	}

	@Override
	public void deleteById(int artProductId) {
		SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        ArtProduct artProd = (ArtProduct) session.get(ArtProduct.class, artProductId);
        session.delete(artProd);
        session.getTransaction().commit();
	}
    
	@Override
	public ArtProduct getArtProductByName(String filename) {
		SessionFactory factory = HibernateUtil.getInstance().getSessionFactory();
		Session session = factory.getCurrentSession();
		session.beginTransaction();
		Query query = session.getNamedQuery("ArtProduct.getByName");
		query.setString("filename", filename);
		return (ArtProduct) query.uniqueResult();
	}
}
